package com.xcm.controller;

import com.google.common.collect.Lists;
import com.xcm.constant.ResponseConstant;
import com.xcm.model.JsonResponse;
import com.xcm.service.ProgramJsonService;
import com.xcm.util.UUIDUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping(value = "/publish")
public class PublishController {
	private static Logger logger = LoggerFactory.getLogger(PublishController.class);
	@Autowired
	private ProgramJsonService programJsonService;
	/**
	 * 广告发布
	 */
	@ResponseBody
	@RequestMapping(value = "/update")
	public Object update(String version, String url, HttpServletRequest request) {
		//验证version
		if (StringUtils.isBlank(version)) {
			return new JsonResponse(1,"参数version不能为空");
		}
		//验证url
		if (StringUtils.isBlank(url)) {
			return new JsonResponse(2,"参数url不能为空");
		}
		try {
			String msg = programJsonService.publishProgram(version, url, request);
			if (StringUtils.isNotBlank(msg)) {
				return new JsonResponse(ResponseConstant.CODE_FAIL, msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("PublishController update 广告发布失败：" + e.getMessage());
			return new JsonResponse(1,"广告发布失败");
		}
		return "";
	}

	/**
	 * TODO 通过导入json文件发布广告
	 *
	 * @param files
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateByJsonFile")
	public Object updateByJsonFile(@RequestParam("files") MultipartFile files) {
		List<JsonResponse> msgList = Lists.newArrayList();
		if (files == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "请选择JSON文件");
		} else if (files.getSize() <= 0) {
			return msgList.add(new JsonResponse(ResponseConstant.CODE_FAIL, "文件内容不能为空"));
		}
		String fileName = files.getOriginalFilename();
		if (StringUtils.isBlank(fileName)) {
			return msgList.add(new JsonResponse(ResponseConstant.CODE_FAIL, "文件名不能为空"));
		}
		String sufix = fileName.substring(fileName.lastIndexOf("."));
		if (!".json".equalsIgnoreCase(sufix)) {
			return msgList.add(new JsonResponse(ResponseConstant.CODE_FAIL, "请选择JSON格式的文件"));
		}
		try {
			String version = UUIDUtils.getUUIDString();
			programJsonService.publishProgramByJsonFile(version, files);
			msgList.add(new JsonResponse(ResponseConstant.CODE_SUCCESS, "导入成功"));
			return msgList;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("PublishController updateByJsonFile 通过导入json文件发布广告：" + e.getMessage());
			return msgList.add(new JsonResponse(1,"通过导入json文件发布广告失败"));
		}
	}

}
